package cn.gogpay.dcb.ixc.cloud.auth.interceptor;

import cn.gogpay.dcb.ixc.cloud.auth.dto.AuthDTO;
import cn.gogpay.dcb.ixc.cloud.auth.utils.AuthContextStore;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: YinHeng
 * @date: 2021/2/7 11:08
 * @description: 请求拦截器
 */
public class AuthRequestPreHandler implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthRequestPreHandler.class);

    private static final String AUTH_HEAD = "auth-user";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String json = request.getHeader(AUTH_HEAD);
        LOGGER.info("cn.gogpay.dcb.ixcloud.auth.interceptor.AuthRequestPreHandler.auth-user:{}", json);
        if (json == null || "".equals(json)) {
            return true;
        }
        AuthDTO authDTO = JSON.parseObject(json, AuthDTO.class);
        AuthContextStore.put(authDTO);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        AuthContextStore.clean();
    }
}
